package org.example.ams.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.example.ams.util.SpringContextUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 自定义websocket连接channel处理器
 * TextWebSocketFrame : 消息类型为文本帧
 * @author cheval
 */
@Slf4j
@ChannelHandler.Sharable
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final ThreadPoolTaskExecutor executorService = SpringContextUtils.getBean("threadPoolTaskExecutor", ThreadPoolTaskExecutor.class);

    /**
     * 从socketChannel读数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) {
        Channel self = channelHandlerContext.channel();
        // 1. 封装消息
        String jsonMsg = textWebSocketFrame.text();
        // 返回发送成功标识
        self.writeAndFlush(new TextWebSocketFrame(jsonMsg));
    }

    /**
     * 客户端连接后的处理
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // id() 唯一id, LongText: 唯一   ShortText: 不唯一
        log.info("客户端：" + ctx.channel().remoteAddress() + " 建立连接，连接的唯一id是:" + ctx.channel().id().asLongText());
    }

    /**
     * 客户端连接断开后的处理
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 移除登录注册
        Channel channel = ctx.channel();
        log.info("客户端：" + ctx.channel().remoteAddress() + " 断开连接");
    }

    /**
     * 通讯过程中异常发生后的处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("通讯发生异常，异常信息为：" + cause.getMessage());
        // 关闭连接
        ctx.close();
    }
}
